import { httpClient, withRetry } from './http';
import {
  Tool,
  CreateToolRequest,
  ApiResponse,
  PaginationParams,
} from '../types';

export class ToolService {
  private static instance: ToolService;

  private constructor() {}

  public static getInstance(): ToolService {
    if (!ToolService.instance) {
      ToolService.instance = new ToolService();
    }
    return ToolService.instance;
  }

  /**
   * 获取所有工具
   */
  public async getAllTools(params?: PaginationParams): Promise<ApiResponse<Tool[]>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<Tool[]>>('/tools', { params }),
      2,
      1000
    )();
  }

  /**
   * 获取活跃工具
   */
  public async getActiveTools(): Promise<ApiResponse<Tool[]>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<Tool[]>>('/tools/active'),
      2,
      1000
    )();
  }

  /**
   * 根据ID获取工具
   */
  public async getTool(id: number): Promise<ApiResponse<Tool>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<Tool>>(`/tools/${id}`),
      2,
      1000
    )();
  }

  /**
   * 创建工具
   */
  public async createTool(tool: CreateToolRequest): Promise<ApiResponse<Tool>> {
    return httpClient.post<ApiResponse<Tool>>('/tools', tool);
  }

  /**
   * 更新工具
   */
  public async updateTool(id: number, tool: Partial<CreateToolRequest>): Promise<ApiResponse<Tool>> {
    return httpClient.put<ApiResponse<Tool>>(`/tools/${id}`, tool);
  }

  /**
   * 删除工具
   */
  public async deleteTool(id: number): Promise<ApiResponse<void>> {
    return httpClient.delete<ApiResponse<void>>(`/tools/${id}`);
  }

  /**
   * 获取工具状态
   */
  public async getToolStatus(id: number): Promise<ApiResponse<{ status: string; health: any }>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<{ status: string; health: any }>>(`/tools/${id}/status`),
      1,
      500
    )();
  }

  /**
   * 批量操作工具
   */
  public async batchUpdateTools(
    toolIds: number[],
    action: 'activate' | 'deactivate' | 'delete',
    data?: Partial<CreateToolRequest>
  ): Promise<ApiResponse<void>> {
    return httpClient.post<ApiResponse<void>>('/tools/batch', {
      tool_ids: toolIds,
      action,
      data,
    });
  }

  /**
   * 获取工具统计信息
   */
  public async getToolStats(): Promise<ApiResponse<{
    total: number;
    active: number;
    inactive: number;
    maintenance: number;
    categories: Record<string, number>;
  }>> {
    return withRetry(
      async () => httpClient.get<ApiResponse<any>>('/tools/stats'),
      2,
      1000
    )();
  }

  /**
   * 搜索工具
   */
  public async searchTools(query: {
    keyword?: string;
    category?: string;
    status?: string;
    page?: number;
    pageSize?: number;
  }): Promise<ApiResponse<{
    items: Tool[];
    total: number;
    page: number;
    pageSize: number;
  }>> {
    return httpClient.get<ApiResponse<any>>('/tools/search', { params: query });
  }

  /**
   * 导出工具配置
   */
  public async exportTools(toolIds?: number[]): Promise<Blob> {
    const params = toolIds ? { tool_ids: toolIds.join(',') } : {};
    const response = await httpClient.get('/tools/export', {
      params,
      responseType: 'blob',
    });
    return response as unknown as Blob;
  }

  /**
   * 导入工具配置
   */
  public async importTools(file: File): Promise<ApiResponse<{
    imported: number;
    failed: number;
    errors: string[];
  }>> {
    const formData = new FormData();
    formData.append('file', file);
    
    return httpClient.post<ApiResponse<any>>('/tools/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });
  }

  /**
   * 测试工具连接
   */
  public async testToolConnection(toolData: {
    url: string;
    config?: Record<string, any>;
  }): Promise<ApiResponse<{
    success: boolean;
    latency?: number;
    error?: string;
  }>> {
    return httpClient.post<ApiResponse<any>>('/tools/test', toolData);
  }

  /**
   * 获取工具日志
   */
  public async getToolLogs(
    id: number,
    params?: {
      level?: 'debug' | 'info' | 'warn' | 'error';
      startTime?: string;
      endTime?: string;
      limit?: number;
    }
  ): Promise<ApiResponse<{
    logs: Array<{
      timestamp: string;
      level: string;
      message: string;
      details?: any;
    }>;
    total: number;
  }>> {
    return httpClient.get<ApiResponse<any>>(`/tools/${id}/logs`, { params });
  }

  /**
   * 重启工具服务
   */
  public async restartTool(id: number): Promise<ApiResponse<void>> {
    return httpClient.post<ApiResponse<void>>(`/tools/${id}/restart`);
  }

  /**
   * 获取工具性能指标
   */
  public async getToolMetrics(
    id: number,
    timeRange?: {
      start: string;
      end: string;
    }
  ): Promise<ApiResponse<{
    cpu: number[];
    memory: number[];
    requests: number[];
    errors: number[];
    timestamps: string[];
  }>> {
    return httpClient.get<ApiResponse<any>>(`/tools/${id}/metrics`, {
      params: timeRange,
    });
  }
}

// 导出单例实例
export const toolService = ToolService.getInstance();

export default toolService;
